<?php
/**
 * 设备共享
 * @author zlj <389843954@qq.com>
 */
namespace app\common\model;
use think\Model;
use app\common\model\Redis;
use app\common\model\Dev_info;
use app\common\model\User;
class Devs_share extends Model
{
	/**
     * 别人共享给我的设备列表
     * @param [int] uid [用户uid]
     * @return [array]
     */
    public function sharelist($uid){
        $field = "d.guid1,d.nickname as devnick,d.name,d.online_inform,d.state,d.tz,u.name as user,u.phone,u.uid,u.nickname,s.id,s.auth,s.valid,s.st,s.et";
        
        $where["s.share_with"] = array((int)$uid,"-1",'or');
        $where["s.accept"] = 1;
        $where["s.valid"] = 1;
        $list2 = self::alias('s')
                    ->join("dev_info AS d ON (d.guid1=s.guid1)","left")
                    ->join("user AS u ON (u.uid=d.owner)","left")
                    ->where($where)
                    ->field($field)
                    ->select();
        $data = array();
        if($list2){
            $redis = new Redis();
            foreach ($list2 as $key => $value) {
                
                if($value["et"]!="0"){
                    if($value["et"]<time() || $value["st"]>time()){
                        //共享时间判断,0:无限制
                        continue;
                    }
                }

                if($value["online_inform"]>0){
                    $redis->select(2);
                }else{
                    $redis->select(0);
                }
                $time = $redis->hget($value["guid1"],"last_upload");

                if($value["user"]){
                    $data[$key]["user"] = $value["user"];
                }elseif($value["phone"]){
                    $data[$key]["user"] = $value["phone"];
                }else{
                    $value['user'] = $value["uid"];
                }

                $nickname = $value['user'];

                $devnick = $value["devnick"]?$value["devnick"]:$value["name"];
                $data[$key]["name"] = $devnick;

                $data[$key]["devname"] = $value["name"];
                $data[$key]["devnick"] = $value["devnick"];

                $data[$key]["id"] = $value["id"];
                $data[$key]["guid1"] = $value["guid1"];
                $data[$key]["time"] = $time;
                $data[$key]["state"] = $value["state"];
                $data[$key]["auth"] = $value["auth"];
                $data[$key]["valid"] = $value["valid"];
                $data[$key]["tz"] = $value["tz"];
                $data[$key]["nickname"] = $nickname;
                $data[$key]["online_inform"] = $value["online_inform"];
                $data[$key]["st"] = $value["st"];
                $data[$key]["et"] = $value["et"];
            }
        }
        return $data;
    }
    
    /**
     * 获取列表
     * @param int $end 结束时间
     * @return array
     * */
    public function getAll($where=[],$field="*"){
        $result = self::field($field);
        
        if ($where){
            $result->where($where);
        }
        $result = $result->select();

        return $result;
    }

    /**
     * 获取某字段信息
     */
    public function getOne($where,$field="*"){
        $result = self::field($field)->where($where)->find();
        if($result){
            $result = $result->getData();
        }
        return $result;
    }

    /**
     * 设备受益人解除共享
     * @param int $id 共享表中的主键id
     * @param int $shareid 用户id
     * @param int $type [false:被共享人用户id  true:设备拥有者]
     * @return boolean  
     */
    public function cancelShare($id,$shareid,$type=false){

        if($type){
            $where["d.owner_id"] = $shareid;
        }else{
            $where["d.share_with"] = $shareid;
        }
        
        $where["d.id"] = $id;

        $return = self::table('devs_share d')->where($where)->field("id")->find();
        if($return){
            $row = self::table('devs_share d')
                        ->join('user u on u.uid=d.share_with')
                        ->field('d.share_with,d.owner_id,d.guid1,u.name,u.phone,u.uid')
                        ->where($where)
                        ->find();

            //删除共享表中的记录
            $flag = self::delete($id);
            
            //清除mysql、redis中的共享受益人报警地址
            $AlarmInfoModel = new Alarm_info();
            $AlarmInfoModel->delAddr($row['guid1'],$row['share_with']);
            return true;
        }else{
            return false;
        }
    }

    /**
     * 查看此设备是否共享给此人
     * @param  [string] $uid    [用户id]
     * @param  [string] $dev_id [设备号]
     * @return [array]
     */
    public function selAuth($uid,$dev_id){

        $where["share_with"] = $uid;
        $where["guid1"] = $dev_id;
        $res = $this->getOne($where);
        
        return $res;
    }

    /**
     * 设备共享信息(已同意、尚未同意、屏蔽警报)
     * @param  [string] $dev_id [设备id号]
     * @param  [string] $uid    [拥有者id]
     * @param  [string] $type   [true 有效  false 所有]
     * @return [array]         [列表]
     */
    public function selDevs($dev_id,$type,$uid=NULL){


        $field = "guid1,owner_id,share_with,st,et,auth,valid,accept";
        $map["guid1"] = $dev_id;
        
        if($type){
            $map["valid"] = 1;
        }
        if($uid){
            $map["owner_id"] = $uid;
        }
        $where['_string'] = 'accept !=0';
        $res = $sharModel->where($map)->field($field)->select();

        return $res;
    }

    /**
     * 检查共享人是否合法
     * @param  [type] $devid [description]
     * @param  [type] $share [description]
     * @return [type]        [description]
     */
    public function checkSharerValid($devid, $share){
        $uid = $_SESSION['uid'];
    
        if(checkEmail($share)){
            //邮箱
            $where["name"] = $share;
        }elseif(strlen($share)<11){
            //用户id
            $where["uid"] = $share;
        }elseif(checkTel($share)){
            //手机号
            $where["phone"] = $share;
        }else{
            return array("state"=>false,"msg"=>"账号格式不正确");
        }
    
    
        //先查此用户是否存在
        $userModel = new User();
    
        $field = 'uid,name,phone,unionid,user_type';
        $shareid = $userModel->getOne($field,$where);

        if(!$shareid){
            return array("state"=>false,"msg"=>"此用户不存在");
        }elseif($shareid["uid"]==$uid){
            return array("state"=>false,"msg"=>"设备不可共享给自己");
        }
        //检查设备是否激活，非激活设备无法共享
        $model = new Dev_info();
        $row = $model->getOne(['guid1'=>$guid1],'state, owner');
        
        if($row["state"] == "inactive"){
            return array('state' => false, 'msg' => '设备未激活，无法设置共享');
        }

        //检查是否已经发过邀请
        $row = $this->getOne(['guid1'=>$devid,'share_with'=>$shareid['uid']],'accept');
        if($row){
            if($row['accept'] == '-1'){
                return array('state' => false, 'msg' => '已发送共享邀请，请勿重新发送');
            }elseif( $row['accept'] == '1' || $row['accept'] == '2'){
                return array('state' => false, 'msg' => '该用户已经在共享列表中，请勿重复共享');
            }else{
                return array('state' => true, 'shareid' => $shareid);
            }
        }
        return array('state' => true, 'shareid' => $shareid);
    }

    /**
     * 添加分享
     * @param [string] $uid  [用户id]
     * @param [string] $dev_id [设备id]
     * @param [string] $share_id [共享给谁]
     */
    public function addShare($uid,$dev_id,$share_id){
    
        $return = false;
    
        $devModel = new Dev_info();

        $where["guid1"] = $dev_id;
        $where["owner"] = $uid;
        $res = $devModel->getOne($where);
        if(!$res){
            //查看此设备是否是此用户的
            return false;
        }

        $add["guid1"] = $dev_id;
        $add["owner_id"] = $uid;
        $add["share_with"] = $share_id;

        $exit = $this->getOne($add,'guid1');
        if($exit){
            //查看是否已添加
            return true;
        }

        $add["st"] = 0;
        $add["et"] = 0;
        $add["auth"] = "SHARE_DATA";
        $add["valid"] =1;
        
        $return = self::add($add);
        
        return true;
    }
}